package com.orangelife.mobile.activities.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.ImageDownloader.ImageSize;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.activities.adapter.ActivityDetailListViewAdapter;
import com.orangelife.mobile.activities.biz.InnerListView;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.buyFresh.activity.BuyOrRegisterActivity;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.confirmOrder.activity.GoodsConfirmOrderActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.individual.activity.MyOrderDetailActivity;
import com.thirdsdk.umeng.UmShareBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.MyScrollview;
import com.orangelife.mobile.web.WebWin;
import com.umeng.socialize.media.UMImage;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 活动团购详情 */
public class ActivityDetailActivity extends OrangeLifeBaseActivity {

    /** 标题栏 */
    private LinearLayout llTitleBar;
    private LinearLayout llTitleBack;
    private ImageButton ibTitileBack;

    private MyScrollview slSlide;
    /** 图片 */
    private ImageView ivPhoto;
    /** 图片下面的标题 */
    private TextView tvTitle;
    /** 图片下面的子标题 */
    private TextView tvChildTitle;
    /** 分享 */
    private ImageButton ibShare;
    /** 内容标题 */
    private TextView tvTitleContent;
    /** 内容 */
    private TextView tvGroupContent;
    /** 说明标题 */
    private TextView tvTips;
    /** 说明 */
    private InnerListView lvTips;
    /** 图片标题 */
    private TextView tvTitlePhoto;
    /** 现价 */
    private TextView tvBuyPriceDiscount;
    /** 原价 */
    private TextView tvBuyPrice;
    /** 规格 */
    private TextView tvWeight;
    /** 参加点击 */
    private TextView tvParticipate;
    /** 活动时间点击 */
    private TextView tvActivityTime;
    /** 报名点击 */
    private Button btnEnter;
    /** 团购linearlayout */
    private LinearLayout llGroup;
    /** 活动linearlayout */
    private LinearLayout llActivity;
    /** 图片 */
    private WebWin wwPhoto;
    /** 分享图片 */
    @SuppressWarnings("unused")
    private UMImage umengImage;
    /** 分享title */
    private String uMtitle = "";
    /** 分享content */
    private String uMcontent = "";
    private Dialog dialog = null;
    /** 接从list传过来的数据 */
    private Map<String, Object> map = null;
    /** 接从后台查来的数据 */
    private Map<String, Object> mapDetail;
    @SuppressWarnings("unused")
    private List<Map<String, Object>> listTips;
    /** 消费说明 */
    List<Map<String, Object>> listSummary;
    /** 规格说明 */
    List<Map<String, Object>> listProducts;
    /** 团购为3，活动为2 */
    private int type;
    private int widthPixels = 0;
    private int heightPixels = 0;
    @SuppressWarnings("unused")
    private Animation ann;
    /** ------------------------------------------ */
    private String merId;
    private ImageDownloader image = ImageDownloader.getImageDownloader();
    private UmShareBiz shareBiz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        shareBiz = new UmShareBiz(this);
        initeView();
        findView();
        setScroll();
    }

    /***
     * 初始化
     */
    private void initeView() {
        llTitleBar = (LinearLayout) findViewById(R.id.llTitle);
        llTitleBack = (LinearLayout) findViewById(R.id.ll_title_back);
        ibTitileBack = (ImageButton) findViewById(R.id.ib_back);

        slSlide = (MyScrollview) findViewById(R.id.slSlide);
        ivPhoto = (ImageView) findViewById(R.id.ivBigPhoto);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvChildTitle = (TextView) findViewById(R.id.tvChildTitle);
        ibShare = (ImageButton) findViewById(R.id.ibShare);
        tvTitleContent = (TextView) findViewById(R.id.tvTitleContent);
        tvGroupContent = (TextView) findViewById(R.id.tvGroupContent);
        tvTips = (TextView) findViewById(R.id.tvTips);
        lvTips = (InnerListView) findViewById(R.id.lvConsumerTips);
        tvTitlePhoto = (TextView) findViewById(R.id.tvTitlePhoto);
        wwPhoto = (WebWin) findViewById(R.id.wwPhoto);
        tvBuyPriceDiscount = (TextView) findViewById(R.id.tvBuyPriceDiscount);
        tvBuyPrice = (TextView) findViewById(R.id.tvBuyPrice);
        tvWeight = (TextView) findViewById(R.id.tvBuyWeight);
        tvParticipate = (TextView) findViewById(R.id.tvParticipate);
        btnEnter = (Button) findViewById(R.id.btnEnter);
        tvActivityTime = (TextView) findViewById(R.id.tvActivityTime);
        llActivity = (LinearLayout) findViewById(R.id.llActivity);
        llGroup = (LinearLayout) findViewById(R.id.llGroup);
    }


    /***
     * 赋值
     */
    @SuppressWarnings("unchecked")
    private void findView() {
        ibShare.setOnClickListener(listener);
        tvParticipate.setOnClickListener(listener);
        Intent intent = getIntent();
        map = (Map<String, Object>) intent.getSerializableExtra("detail");
        getDataFromServer();
        getActivityDetail();
    }

    private void setScroll() {
        llTitleBar.getBackground().setAlpha(0);
        slSlide.setScrollListener(new MyScrollview.ScrollViewListener() {
            @Override
            public void scorlling(int scrollY, int oldScrollY) {
                int alphaNow = 255;
                alphaNow = (int) (scrollY < 200 ? alphaNow * (scrollY / 200.0f) : 255);
                llTitleBar.getBackground().setAlpha(alphaNow);
                if (alphaNow > 200) {
                    ibTitileBack.setBackgroundResource(R.drawable.back_orange);
                } else {
                    ibTitileBack.setBackgroundResource(R.drawable.ic_shadow_back);
                }

            }
        });
    }


    /**
     * 设置详情
     */
    @SuppressWarnings("unchecked")
    private void setDetail() {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        widthPixels = mDisplayMetrics.widthPixels;
        heightPixels = (int) (widthPixels * (9 / 16f));
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
                widthPixels, widthPixels);
        ivPhoto.setLayoutParams(mParams);
        uMtitle = mapDetail.get("actvtName").toString();/* 店铺名称 */
        uMcontent = mapDetail.get("description").toString();/* 店铺名称 */
        merId = mapDetail.get("actvtID").toString();
        type = Integer.parseInt(mapDetail.get("actvtType").toString());
        image.download(mapDetail.get("cover").toString().trim(), ivPhoto,
                ImageSize.IMAGE_SIZE_MIDDLE_JPG);
        tvTitle.setText(mapDetail.get("actvtName").toString());
        String childTitle = mapDetail.get("tip").toString();
        if (!StringUtil.isBlank(childTitle)) {
            tvChildTitle.setText(mapDetail.get("tip").toString());
        } else {
            tvChildTitle.setText("");
        }
        int status = Integer.parseInt(mapDetail.get("status").toString());
        tvGroupContent.setText(mapDetail.get("description").toString());
        listSummary = (List<Map<String, Object>>) mapDetail.get("summary");
        setWebView();
        if (type == 2) {
            DateUtil dateUtil = new DateUtil();
            tvTitleContent.setText(R.string.activity_content);
            tvTips.setText(R.string.activity_tips);
            tvTitlePhoto.setText(R.string.wonderfu_photo);
            String starTime = dateUtil.tranStringForDate_1(mapDetail
                    .get("startTime").toString().trim());
            String endTime = dateUtil.tranStringForDate_1(mapDetail
                    .get("endTime").toString().trim());
            tvActivityTime.setText(starTime + "至" + endTime);
            listProducts = new ArrayList<Map<String, Object>>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actvtID", mapDetail.get("actvtID"));
            ActivityDetailListViewAdapter adapter = new ActivityDetailListViewAdapter(
                    this, listSummary);
            lvTips.setAdapter(adapter);
            setListViewHeightBasedOnChildren(lvTips);
            listProducts.add(map);
            btnEnter.setOnClickListener(listener);
            llGroup.setVisibility(View.GONE);
            btnEnter.setText(R.string.apply);
            if (status == 1) {
                btnEnter.setBackgroundResource(R.drawable.selector_btn_right_angle_orange);
            } else if (status == 0) {
                btnEnter.setBackgroundResource(R.color.text_color_gray);
            }

        } else if (type == 3) {
            tvTitleContent.setText(R.string.group_content);
            tvTips.setText(R.string.consumer_tips);
            tvTitlePhoto.setText(R.string.trade_photo);
            listProducts = (List<Map<String, Object>>) mapDetail
                    .get("products");
            if (listProducts.size() != 0) {
                Map<String, Object> products = new HashMap<>();
                products = listProducts.get(0);
                tvBuyPriceDiscount.setText(Constant.RMB_FLAG
                        + String.valueOf(products.get("price")));
                tvBuyPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                tvBuyPrice.setText(Constant.RMB_FLAG
                        + String.valueOf(products.get("mkPrice")));
                tvWeight.setText(String.valueOf(products.get("pdtDesc")));
            }
            ActivityDetailListViewAdapter adapter = new ActivityDetailListViewAdapter(
                    this, listSummary);
            lvTips.setAdapter(adapter);
            setListViewHeightBasedOnChildren(lvTips);
            tvParticipate.setOnClickListener(listener);
            llActivity.setVisibility(View.GONE);
            tvParticipate.setText(R.string.tuxedo);
            if (status == 1) {
                tvParticipate.setBackgroundResource(R.drawable.selector_btn_right_angle_orange);
            } else if (status == 0) {
                tvParticipate.setBackgroundResource(R.color.text_color_gray);
            }
        }

    }

    /**
     * 设置listview高度
     *
     * @param listView
     */
    private void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ActivityDetailListViewAdapter listAdapter = (ActivityDetailListViewAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 设置照片的webview
     */
    private void setWebView() {
        String pics = mapDetail.get("pics").toString();
        wwPhoto.loadDataWithBaseURL(pics);
    }

    /**
     * 是否绑定手机
     *
     * @return
     */
    @SuppressWarnings("unused")
    private boolean isRegister() {
        if (StringUtil.isBlank(UserSp.getRegPhone())) {
            return false;
        }
        return true;
    }

    private OnClickListener listener = new OnClickListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ibShare:
                    shareBiz.share(uMtitle, uMcontent, Constant.ACTIVITY_UNDERLINE_URL, merId);
                    break;
                case R.id.tvParticipate:
                /* 实例化SelectPicPopupWindow */
				/*
				 * 是先显示免注册提交还是先显示选择规格 （1表示先显示先注册）
				 */
                    int status = Integer.parseInt(mapDetail.get("status").toString());
                    if (status == 0) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.group_out_of_date));
                    } else {
                        if (mapDetail != null) {
                            List<Map<String, Object>> listProduct = new ArrayList<Map<String, Object>>();
                            listProduct = (List<Map<String, Object>>) mapDetail.get("products");
                            ExitApplication.getInstance().addFailActivity(ActivityDetailActivity.this);
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("actvtID", mapDetail.get("actvtID").toString());
                            map.put("sellPloyID", mapDetail.get("sellPloyID"));
                            map.put("merchantName", mapDetail.get("merchantName"));
                            map.put("productID", listProduct.get(0).get("productID").toString());
                            map.put("orderNumber", "1");
                            map.put("totalPrice", listProduct.get(0).get("price").toString());
                            map.put("mkPrice", listProduct.get(0).get("mkPrice").toString());
                            map.put("pdtDesc", listProduct.get(0).get("pdtDesc").toString());
                            map.put("shipCost", mapDetail.get("shipCost"));
                            map.put("goodsLogo", mapDetail.get("cover"));
                            map.put("title", mapDetail.get("actvtName").toString());
                            map.put("isScore", false);
                            map.put("active", 3);
                            map.put("limits", listProduct.get(0).get("limits").toString());
                            if (getIntent().getBooleanExtra("score", false)) {
                                map.put("score", listProduct.get(0).get("score").toString());
                                map.put("isScore", true);
                            }
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("map", (Serializable) map);
                            Intent intent = new Intent();
                            intent.putExtras(bundle);
                            intent.setClass(ActivityDetailActivity.this, GoodsConfirmOrderActivity.class);
                            startActivity(intent);
                        }
                    }
                    break;
                case R.id.btnEnter:
                    status = Integer.parseInt(mapDetail.get("status").toString());
                    if (status == 0) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.activity_out_of_date));
                    } else {
                        if (mapDetail != null) {
                            ExitApplication.getInstance().addFailActivity(ActivityDetailActivity.this);
                            Intent intent = new Intent();
                            Bundle bundle = new Bundle();
                            intent.putExtra("active", 2);
                            bundle.putSerializable("specification",
                                    (Serializable) mapDetail);
                            intent.putExtras(bundle);
                            intent.setClass(ActivityDetailActivity.this,
                                    BuyOrRegisterActivity.class);
                            startActivity(intent);
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    };

    /** 弹出对话框 */
    private void isValidateDialog() {
        final ConfirmDialog confirmDialog = new ConfirmDialog(ActivityDetailActivity.this, "温馨提示", "报名线下活动会扣除" + mapDetail.get("score").toString() + "积分，是否要报名？", "取消", "报名");
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                confirmDialog.dismiss();
                return;
            }

            @Override
            public void doRight() {
                confirmDialog.dismiss();
                int score = Integer.parseInt(mapDetail.get("score")
                        .toString());
                int myScore = Integer.parseInt(UserSp.getPoint());
                if (myScore < score) {
                    ToastHelper.getInstance()._toast("您的积分不足，暂时不能支付");
                }
                setOrder();
            }
        });

        confirmDialog.show();
    }


    private void isValidateDialog1() {
        AlertDialog.Builder builder = new Builder(ActivityDetailActivity.this);
        builder.setMessage("报名线下活动会扣除" + mapDetail.get("score").toString() + "积分，是否要报名？");
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                return;
            }
        });
        builder.setNegativeButton("报名", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                int score = Integer.parseInt(mapDetail.get("score")
                        .toString());
                int myScore = Integer.parseInt(UserSp.getPoint());
                if (myScore < score) {
                    ToastHelper.getInstance()._toast("您的积分不足，暂时不能支付");
                }
                setOrder();
            }
        });
        builder.create().show();
    }

    /** 将添加的数据上传上去 */
    @SuppressWarnings("deprecation")
    private void setOrder() {
        try {
            map = new HashMap<>();
            map.put("actvtID", listProducts.get(0).get("actvtID"));
            // map.put("shipName", "张三");
            map.put("shipPhone", UserSp.getRegPhone());
            Map<String, Object> rootMap = new HashMap<>();
            rootMap.put("map", map);
            rootMap.put("url", Constant.URL_UNDERLINE_ADD);
            rootMap.put("wat", 15);
            new JSONRequest(JSONRequest.POST, rootMap, handler,
                    HttpUtil.ACTION_JSON);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 15:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    String orderID = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("orderID").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        finish();
                        ToastHelper.getInstance()._toast(
                                getResources().getString(R.string.submit_success));
                        if (type == 2) {
                            return;
                        }
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        Map<String, Object> mapOrder = new HashMap<String, Object>();
                        mapOrder.put("orderID", orderID);
                        mapOrder.put("orderType", type);
                        bundle.putSerializable("map", (Serializable) mapOrder);
                        intent.setClass(ActivityDetailActivity.this,
                                MyOrderDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
                case 6:
                    DialogHelper.closeDialog(dialog);
                    mapDetail = new HashMap<String, Object>();
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    setDetail();
                    break;

                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog, ActivityDetailActivity.this);
                    break;
                case 1:
				/*
				 * 返回参数 "scoreResult": "0", "score": "15", "scoreExchange": "1",
				 * "sponit":"5"
				 */
                    final Map<String, Object> map = (Map<String, Object>) JSONHelper
                            .jsonToMap(msg.obj.toString()).get("entity");
                    if (map != null) {
                        String scoreResult = map.get("scoreResult").toString();
                        String sponit = map.get("sponit").toString();
                        if (scoreResult.equals("0")) {
                            UserSp.setPoint(String.valueOf(map.get("score")));
                            if (!StringUtil.isBlank(UserSp.getLoginID())) {
                                ToastHelper.getInstance()._toast("恭喜您获得了" + sponit + "积分");
                            }
                        }
                    }
                    break;
                case 15001:
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.goods_undercarriage));
                    btnEnter.setEnabled(false);
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 获得详情
     */
    @SuppressWarnings("deprecation")
    private void getActivityDetail() {
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        @SuppressWarnings("unused")
        int type = 0;
        String actvID;
        if (map != null) {
//			type = Integer.parseInt(map.get("actvtType").toString());
            actvID = map.get("actvtID").toString();
        } else {
            Intent intent = getIntent();
//			type = intent.getIntExtra("actvtType", 2);
            actvID = intent.getStringExtra("actvtID");
            if (StringUtil.isBlank(actvID)) {
                actvID = intent.getStringExtra("id");
            }
        }
        mapSubmit.put("{actvtID}", actvID);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", mapSubmit);
//		if (type == 2) {
//			rootMap.put("url", Constant.URL_UNDERLINE_ACTIVITY);
//		} else if (type == 3) {
        rootMap.put("url", Constant.URL_GROUP_ACTIVITY);
//		}
        rootMap.put("wat", 6);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 15:
                isValidateDialog();
                break;
            case 2:
                ToastHelper.getInstance()._toast("您的积分不足，暂时不能支付");
                break;

            default:
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        BLog.getInstance().inMerDetail(UserSp.getLoginID());
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BLog.getInstance().outMerDetail(UserSp.getLoginID());
    }
}
